﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using DataLayer.dbml;
using DataLayer.Controller;
using obout_ASPTreeView_2_NET;
using OboutInc.Flyout2;


public partial class services_ViewOpportunities : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        this.configExport();
        this.Grid1.SelectedRecords = null;
        if (!IsPostBack)
        {
            //this.hdnNIT.Value = "900092385-00";
            //loadTree("900092385-00");
            if (Request.QueryString["NIT"] != null)
            {
                this.hdnNIT.Value = Request.QueryString["NIT"].ToString();

                //Trae el idCuenta del nit
                CUENTA cta = AccountController.GetCuentaByNit(this.hdnNIT.Value);
                this.hdnIdCuenta.Value = cta.ID_CUENTASFDC;

                loadTree(Request.QueryString["NIT"].ToString());                
            }
            
        }
        else
        {
            //Se genero el postback desde el treeview o se esta paginando
            this.loadGrid();
            if (this.hdnPostBackTree.Value.ToString().Equals("1"))
                this.hdnPostBackTree.Value = "0";

            this.txtSearch.Text = string.Empty;
        }        
    }


    /// <summary>
    /// carga el arbol
    /// </summary>
    private void loadTree(string nit)
    {
        obout_ASPTreeView_2_NET.Tree oTree = new obout_ASPTreeView_2_NET.Tree();
        oTree.FolderIcons = "../style/tree2/icons";
        oTree.FolderScript = "../style/tree2/script";
        oTree.FolderStyle = "../style/tree2/style/Classic";
        oTree.ShowRootIcon = true;
        oTree.ShowRootPlusMinus = true;
        oTree.AddRootNode("<div onmouseover=\"CursorMano(this); \">Todos</div>", true, "folderOpen16.jpg");
        oTree.EventList = "OnNodeSelect";

        string paramSearch = string.Empty;
        string attachTo = string.Empty;

        List<CLIENTE_FINAL> listClient = FinalClientController.GetAllByCuenta(nit, paramSearch);

        tblError.Visible = false;
        if (listClient.Count() <= 0)
        {
            tblError.Visible = true;
            return;
        }

        foreach (CLIENTE_FINAL cf in listClient)
        {
            oTree.Add("root", "0" + cf.ID_CLIENTEFINALSDFC, "<div onmouseover=\"CursorMano(this); \">" + cf.NOMBRE_CLIENTEFINAL + "</div>", true, "folderOpen16.jpg");
            attachTo += "0" + cf.ID_CLIENTEFINALSDFC + ",";

            paramSearch = string.Empty;

            //if (ddlTypeSearch.SelectedValue == "2")
            //    paramSearch = txtSearch.Text;

            List<PROYECTO> listpt = ProjectController.GetAllByFinalClient(cf.ID_CLIENTEFINALSDFC, paramSearch, this.hdnIdCuenta.Value);
            foreach (PROYECTO pt in listpt)
            {
                oTree.Add("0" + cf.ID_CLIENTEFINALSDFC, "1" + pt.ID_PROYECTOSFDC, "<div onmouseover=\"CursorMano(this); \">" + pt.NOMBRE_PROYECTO + "</div>", true, "folderOpen16.jpg");
                attachTo += "1" + pt.ID_PROYECTOSFDC + ",";

                paramSearch = string.Empty;

                //if (ddlTypeSearch.SelectedValue == "3")
                //    paramSearch = txtSearch.Text;

                List<OPORTUNIDAD> listOpor = OpportunityController.GetAllByProject(pt.ID_PROYECTOSFDC);
                foreach (OPORTUNIDAD opo in listOpor)
                {
                    oTree.Add("1" + pt.ID_PROYECTOSFDC, "2" + opo.ID_OPORTUNIDADSDFC, "<div onmouseover=\"CursorMano(this); \">" + opo.NOMBRE_OPORTUNIDAD + "</div>", true, "Services21.jpg");
                }
            }
        }

        this.trvClient.Text = oTree.HTML();

        if (attachTo.Length > 0)
            attachTo = attachTo.Substring(0, attachTo.Length - 1);

        Flyout2.AttachTo = attachTo;
        Flyout2.OpenEvent = OpenEvents.ONRIGHTCLICK;
        Flyout2.Position = PositionStyle.MIDDLE_RIGHT;

    }

    /// <summary>
    /// Configura las opciones que se utilizaran para exportar la grilla
    /// </summary>
    private void configExport()
    {
        this.Grid1.ExportingSettings.AppendTimeStamp = false;
        this.Grid1.ExportingSettings.ExportAllPages = true;
        this.Grid1.ExportingSettings.ExportHiddenColumns = true;
        this.Grid1.ExportingSettings.FileName = "Oportunidades";
        this.Grid1.ExportingSettings.KeepColumnSettings = false;
        this.Grid1.ExportingSettings.ExportTemplates = true;
        this.Grid1.ExportingSettings.ColumnsToExport = null;
    }

    private void loadGrid()
    {
        this.Grid1.DataSource = null;
        this.Grid1.DataBind();

        if ((this.hdnNodoSeleccionado.Value.ToString().Length > 0) || (this.hdnRightClickSeleccionado.Value.ToString().Length > 0) || (this.txtSearchVisible.Text.Trim().Length > 0))
        {
            string paramSearch = this.txtSearch.Text.Trim();
            paramSearch = paramSearch.Replace(",", "");

            if (paramSearch.Length == 0)
            {
                paramSearch = this.txtSearchVisible.Text.Trim();
                paramSearch = paramSearch.Replace(",", "");
            }

            //Se obtiene el nivel del nodo seleccionado, que esta en el id
            int nivelNodo = 0;
            string idNodo = string.Empty;
            if (this.hdnNodoSeleccionado.Value.ToString().Length > 0)
            {
                if (this.hdnNodoSeleccionado.Value.ToString().Equals("root_tree1"))
                {
                    nivelNodo = -1;
                    idNodo = "0";
                }
                else
                {
                    nivelNodo = Convert.ToInt32(this.hdnNodoSeleccionado.Value.ToString().Substring(0, 1));
                    idNodo = this.hdnNodoSeleccionado.Value.ToString().Substring(1);                
                }
            }
            else if (this.hdnRightClickSeleccionado.Value.ToString().Length > 0)
            {
                nivelNodo = Convert.ToInt32(this.hdnRightClickSeleccionado.Value.ToString().Substring(0, 1));
                idNodo = this.hdnRightClickSeleccionado.Value.ToString().Substring(1);
            }


            //Se determina si se busca por cliente, proyecto o servicio, dependiendo del nodo seleccionado
            DataLayer.Utilities.PropertiesApp.Jerarquia jerarquia = DataLayer.Utilities.PropertiesApp.Jerarquia.Cliente;
            if (nivelNodo == 2)
                jerarquia = DataLayer.Utilities.PropertiesApp.Jerarquia.Servicio;
            else if (nivelNodo == 1)
                jerarquia = DataLayer.Utilities.PropertiesApp.Jerarquia.Proyecto;
            else if (nivelNodo == 0)
                jerarquia = DataLayer.Utilities.PropertiesApp.Jerarquia.Cliente;
            else if (nivelNodo == -1)
                jerarquia = DataLayer.Utilities.PropertiesApp.Jerarquia.Todos;


            DataTable dttDetail = OpportunityController.GetOpportunityDetail(idNodo, jerarquia, paramSearch, this.hdnIdCuenta.Value);

            this.Grid1.DataSource = dttDetail;
            this.Grid1.DataBind();

            //Se guarda en session la tabla de los resultados, para poder filtrar
            Session["VIEWOPPORTUNITIES"] = dttDetail;
        }
    }


    protected void btnSearch_Click(object sender, ImageClickEventArgs e)
    {
        //Se hizo busqueda con el click derecho sobre el arbol, se tiene en cuenta solamente el nodo sobre
        //el que se dio click derecho
        this.hdnNodoSeleccionado.Value = "";
        //No se de donde aparecen estas comas en el textbox
        this.txtSearch.Text = this.txtSearch.Text.Replace(",", "");

        //this.loadGrid();
        txtSearch.Text = string.Empty;
        this.hdnRightClickSeleccionado.Value = "";
    }

    protected void btnSearchVisible_Click(object sender, ImageClickEventArgs e)
    {
        //Se hizo busqueda con el click derecho sobre el arbol, se tiene en cuenta solamente el nodo sobre
        //el que se dio click derecho
        this.hdnNodoSeleccionado.Value = "";
        //No se de donde aparecen estas comas en el textbox
        this.txtSearch.Text = this.txtSearch.Text.Replace(",", "");
        this.txtSearchVisible.Text = this.txtSearchVisible.Text.Replace(",", "");

        //this.loadGrid();
        txtSearch.Text = string.Empty;
        txtSearchVisible.Text = string.Empty;
        this.hdnRightClickSeleccionado.Value = "";
    }



    #region "Filtros de la grilla"

    protected void btnBuscarGrilla_Click(object sender, ImageClickEventArgs e)
    {
        if (string.IsNullOrEmpty(this.txtContiene.Text.Trim()))
            return;

        if (Session["VIEWOPPORTUNITIES"] != null)
        {
            DataTable dtt = (DataTable)Session["VIEWOPPORTUNITIES"];
            string columna = this.hdnColumnaSeleccionada.Value.ToString();

            DataView dw = dtt.DefaultView;
            dw.RowFilter = columna + " LIKE '%" + this.txtContiene.Text.Trim() + "%'";
            dtt = dw.ToTable();

            this.Grid1.DataSource = dtt;
            this.Grid1.DataBind();
            Session["VIEWOPPORTUNITIES"] = dtt;

            this.txtContiene.Text = string.Empty;
        }
    }

    protected void lnkAscendente_Click(object sender, EventArgs e)
    {
        if (Session["VIEWOPPORTUNITIES"] != null)
        {
            DataTable dtt = (DataTable)Session["VIEWOPPORTUNITIES"];
            string columna = this.hdnColumnaSeleccionada.Value.ToString();

            DataView dw = dtt.DefaultView;
            dw.Sort = columna + " ASC";
            dtt = dw.ToTable();

            this.Grid1.DataSource = dtt;
            this.Grid1.DataBind();
            Session["VIEWOPPORTUNITIES"] = dtt;
        }
    }

    protected void lnkDescendente_Click(object sender, EventArgs e)
    {
        if (Session["VIEWOPPORTUNITIES"] != null)
        {
            DataTable dtt = (DataTable)Session["VIEWOPPORTUNITIES"];
            string columna = this.hdnColumnaSeleccionada.Value.ToString();

            DataView dw = dtt.DefaultView;
            dw.Sort = columna + " DESC";
            dtt = dw.ToTable();

            this.Grid1.DataSource = dtt;
            this.Grid1.DataBind();
            Session["VIEWOPPORTUNITIES"] = dtt;
        }
    }

    protected void lnkSinFiltro_Click(object sender, EventArgs e)
    {
        this.loadGrid();
    }

    #endregion



    protected void btnCrearOportunidad_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("Opportunity.aspx");
    }
}
